package com.studyroom.component;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.studyroom.dto.ChatMessage;
import com.studyroom.dto.Mail;
import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


import static com.studyroom.utils.RabbitMqContants.CHAT_SOLO_QUEUE_TOPIC;
import static com.studyroom.utils.RabbitMqContants.MAIL_QUEUE_TOPIC;
import static com.studyroom.utils.RedisContants.*;

@Component
@Slf4j
public class Receiver {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //接受聊天消息
    @RabbitListener(queues = CHAT_SOLO_QUEUE_TOPIC)
    public void chatSoloReceiver(String msg, Channel channel, Message message){
        try{
            String chatMessageJson=new String (message.getBody ());
            ChatMessage chatMessage= JSONUtil.toBean (chatMessageJson,ChatMessage.class);
            //存入redis
            String chatSoloKey=CHAT_SOLO_KEY+chatMessage.getId ();
            stringRedisTemplate.opsForList ().rightPush (chatSoloKey,chatMessageJson);
        }catch (Exception e){
            e.printStackTrace ();
        }
    }
    @RabbitListener(queues = MAIL_QUEUE_TOPIC)
    public void mailReceiver(String msg,Channel channel,Message message){
        try{
            String mailJson=new String (message.getBody ());
            Mail mail=JSONUtil.toBean (mailJson,Mail.class);
            //存入redis
            String mailKey=MAIL_KEY+mail.getReceiver ();
            stringRedisTemplate.opsForList ().leftPush (mailKey,mailJson);
        }catch (Exception e){
            e.printStackTrace ();
        }
    }
}
